<?php
// +----------------------------------------------------------------------
// | 可视化管理
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\CemeteryModel;
use app\admin\model\MwProductLogModel;
use app\admin\model\ProductInfoModel;
use app\admin\model\TombareaModel;
use app\admin\model\TombareaRowColModel;
use cmf\controller\AdminBaseController;
use function Composer\Autoload\includeFile;
use function Qiniu\entry;
use think\Db;
use app\admin\model\AdminMenuModel;
use think\Exception;
use tree\Tree;

class VisuaController extends AdminBaseController
{

    protected $selected_id_v = 0;
    protected $cemetery_model;

    public function initialize()
    {
        $this->selected_id_v = session('selected_id_v');
        $this->cemetery_model = new CemeteryModel();
        parent::initialize();
    }

    public function getSup($id){
        // 拼接查询条件hql
        $res= $this->cemetery_model->where(array('is_delete'=>0,'id'=>$id))->select()->toArray();
		// 得到一级数据
		if($res) {
            if($res[0]["parent_id"] != 0) {
                $result = $this->getSup($res[0]["parent_id"]);
            }else{
                $result = array();
            }
            $imgInfo = array_merge_recursive($res, $result);
        }else{
            $imgInfo = array();
        }
        return $imgInfo;
    }
	public function index(){
        $name = $this->request->param("name");

        if(empty($name)){
            $result = $this->cemetery_model->cacheCemeteryData();
        }else{
//            $result = $model->getListTreeWhere();

            $result =  $this->cemetery_model->alias("c")
                ->field("c.id,c.name,c.parent_id as pId,c.type")
                ->join("dj_tombarea t","c.id = t.cemetery_id","left")
                ->join("dj_tombarea_row r","t.id = r.tombarea_id","left")
                ->join("dj_tombarea_row_col rc","r.rowID = rc.rowid","left")
                ->where('c.is_delete',0)
                ->where('rc.num',$name)
                ->order(array("c.list_order" => "ASC"))
                ->select()->toArray();
        }
        $tom = array();
        foreach($result as $k => $v){
            $tombarea = Db::name("tombarea")->field("id,name,'' as type")
                ->where(array("cemetery_id"=>$v["id"],"status"=>1))->order('list_order asc ')
                ->select()->toArray();
            foreach($tombarea as $i => $t){
                $tombarea[$i]['pId'] = $v["id"];
            }
            $tom = array_merge_recursive ( $tom, $tombarea);
        }
        $result = array_merge_recursive ( $tom, $result);

        $this->assign("categorys", json_encode($result));
        $this->assign("name", $name);
        //选中的ID
        $this->assign("selected_id_v", $this->selected_id_v?$this->selected_id_v:0);
		return $this->fetch();
	}
	/*
	 * 根据陵园查询墓区
	 */
	public function selectTombarea(){
        $id = $this->request->param("id");
        $result = Db::name("dj_tombarea")->field("id,t.align,t.row,p.selling_price")
            ->where(array('t.cemetery_id'=>$id,'t.status'=>1))->select()->toArray();

        exit(json_encode($result));
    }
	/*
	 * 根据陵园查询墓位信息
	 */
	public function tombareacol($ajax=0){
	    if($ajax==1){
            if ($this->request->isPost()) {
                $post = $this->request->param();
               $result =  TombareaModel::update([$post['name']=>$post['value'],'add_time'=>time()],['id'=>$post['node']]);
               if ($result===false){
                   return $this->error('修改失败');
               }else{
                   return $this->success('参数保存成功！');
               }
            }
        }else {
            $id = $this->request->param("id");
            $array_list = TombareaRowColModel::getTombRowColById($id);
            $result['data'] = $array_list;
            exit(json_encode($result));
        }
    }

	/*
	 * 陵园墓区产品信息
	 */
	public function product(){
        $tombar_id = $this->request->param('tombar_id');
        $this->assign("tombar_id",$tombar_id);
        $type = $this->request->param('type');
        $this->assign("type",$type);

        $tomb_id = $this->request->param('tomb_id');
        $selected_id_v = $this->request->param('selected_id_v');
        session('selected_id_v', isset($selected_id_v)?$selected_id_v:'0');

        $info = Db::name("tombarea_row_col")->alias("c")
            ->join("dj_tombarea_information_product p","c.colID = p.tomb_id","left")
            ->whereIn('c.colID',$tomb_id)->find();
        $num='';
        if ($info){
            $result = Db::name('tombarea_information_product')->alias("t")
                ->field("t.*,p.stele_type")
                ->join("dj_product p","t.new_pro = p.id","left")
                ->where(['tomb_id'=>$info['colID'],'cate_id'=>$info['cate_id']])
                ->find();
            if ($result){
                if ($result['single_cavity_size']) {
                    $single_cavity_size = explode('*', $result['single_cavity_size']);
                    $result['sc_width'] = $single_cavity_size[0];
                    $result['sc_height'] = $single_cavity_size[1];
                    $result['sc_thick'] = $single_cavity_size[2];
                }
                $result['reacher'] = $info['reacher'];
            }
            $num  = $info['num'];
            $cate_id = $info['cate_id'];
            if ($cate_id==2){
                // 详情
                $mb_list =  Db::name('tomb_mb')->where(['mb.tomb_id'=>$info['colID']])->alias('mb')
                    ->field('mb.tomb_id,mb.mb_id,mb.mb_name,mp.pro_name,mb.address')
                    ->leftJoin('dj_product_mb mp','mb.mb_id = mp.id')
                    ->where(['mb.type'=>0])
                    ->select();
                $this->assign('baseData', $mb_list);
            }
        }

//        // 石材种类
        $cate_type = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name")-> join("dj_cate c","c.id = s.cate_id","left") ->select();
        $this->assign("cate_type",json_encode($cate_type));
//        // 附件
        $annex = Db::name("annex")->field("id,annex_name as name")->select();
        $this->assign("annexJson", json_encode($annex));

        $this->this_tomb();

        // 抵顶人
        $diding = Db::name("user")->alias("u")->field("user_nickname")
            ->join("dj_department d","d.id = u.dept_id","left")
            ->where("d.dept_type",7)
            ->where("u.user_status",1)
            ->select();
        $this->assign("didingList", $diding);
        $mb_arr=[];
        $mblist=  Db::name('product')->where(['pro_type'=>$cate_id,'pro_status'=>1])->select();

        foreach ($mblist as $km=>&$vals){
            $m_info['id'] = $vals['id'];
            $m_info['pro_name'] = $vals['pro_name'].'('.$vals['pro_code'].')【'.$this->regulation_arr[$vals['regulation']].'】';
            $m_info['pro_code'] = $vals['pro_code'];
            $m_info['pro_photo'] = $vals['pro_photo'];
            $m_info['pro_photo_path'] = cmf_get_image_preview_url($vals['pro_photo']);
            $mb_arr[]=$m_info;
        }
        // 陵园id
        $cemeData = Db::name("tombarea")->alias('s')->field("c.id,c.parent_id")->join("dj_cemetery c","c.id = s.cemetery_id","left")->where(array('s.id'=>$tombar_id)) ->find();
        $this->assign("ceme_id", $cemeData['id']);
        $this->assign("parent_id", $cemeData['parent_id']);

        if ($cate_id == 2 ){
            $tomb_mb_list = Db::name("tomb_mb")->where(['tomb_id'=>$tomb_id,'type'=>0])->select();
            $result['infoData'] = $tomb_mb_list;
        }

        $this->assign('info',$info);
        $this->assign('cate_id',$cate_id);
        $this->assign('result',$result);
        $this->assign('num_sn',$num);
        $this->assign('col_id',$tomb_id);
        $mblist=  Db::name('product')->where('pro_type', $cate_id)->select();
        $this->assign('mb_list',$mblist);

        return $this->fetch();
    }

    public function getProductInfo(){
        $id = $this->request->param("id");
        $itype = $this->request->param("type",1);
        $othData = [];
        if ($itype != 2){
            $data = Db::name("product")->alias('s')->field("s.*,p.pro_name as name")
                -> join("dj_product p","p.id = s.change_id","left")->where(array("s.id"=>$id)) ->find();
            $infoData = ProductInfoModel::where(['pro_id' => $id,'itype' => 1])->select();
            $baseData = ProductInfoModel::where(['pro_id' => $id,'itype' => 2])->select();
            $plateData = ProductInfoModel::where(['pro_id' => $id,'itype' => 3])->select();
            $railData = ProductInfoModel::where(['pro_id' => $id,'itype' => 4])->select();
            $annexData = Db::name("product_annex")->where(['pro_id' => $id])->select();
        }else{
            $mwid = $this->request->param("mwid");
            $data = Db::name("product_mb")->where(['id' => $id])->find();
            $infoData =  Db::name("product_mb_info")->where(['pro_id' => $id,'itype' => 1])->select();
            $baseData =  Db::name("product_mb_info")->where(['pro_id' => $id,'itype' => 2])->select();
            $plateData =  Db::name("product_mb_info")->where(['pro_id' => $id,'itype' => 3])->select();
            $railData =  Db::name("product_mb_info")->where(['pro_id' => $id,'itype' => 4])->select();
            $annexData = Db::name("product_mb_annex")->where(['mb_id' => $id])->select();
            $othData =  Db::name("product_mb_info")->where(['mb_id' => $mwid,'itype' => 7])->select();
        }

        $result = array(
            'infoData' => $infoData,
            'baseData' => $baseData,
            'plateData' => $plateData,
            'railData' => $railData,
            'annexData' => $annexData,
            'othData'=>$othData,
            'data'=>$data
        );

        exit(json_encode($result));
    }
    public function productadd_post(){

        // 墓区id
        $tombar_id = $this->request->param('tombar_id');
        $data = $this->request->param();
        if($data['id'] != 0){
            Db::name("tombarea_product")->where('id', $data['id']) ->delete();
        }

        $productData['tombar_id'] = $tombar_id;
        $productData['pro_status'] = $data['pro_status'];
        $productData['footprint'] = $data['footprint'];
        $productData['tombstone_h'] = $data['tombstone_h'];
        $productData['tomb_regulation'] = $data['tomb_regulation'];
        $productData['warranty'] = $data['warranty'];
        $productData['specifications'] = $data['specifications'];
        $productData['green_belt'] = $data['green_belt'];
        $productData['selling_price'] = $data['selling_price'];
        $productData['manage_cycle'] = $data['manage_cycle'];
        $productData['supplier'] = $data['supplier'];
        $productData['old_pro'] = $data['old_pro'];
        $productData['new_pro'] = $data['new_pro'];
//        $productData['pro_photo'] = $data['pro_photo'];
        $productData['add_user'] = cmf_get_current_admin_id();
        $productData['add_time'] = time();

        Db::name("tombarea_product")->insert($productData);
        // 陵园id
        $cemeData = Db::name("tombarea")->alias('s')->field("c.id,c.parent_id")-> join("dj_cemetery c","c.id = s.cemetery_id","left")->where(array('s.id'=>$tombar_id)) ->find();
        $id = $cemeData['id'];
        $parent_id = $cemeData['parent_id'];

        $this->success("保存成功",url("visua/index"));
    }
    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
	protected function _get_level($id, $array = array(), $i = 0) {
        if ($array[$id]['parent_id']==0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id']==$id){
            return  $i;
        }else{
            $i++;
            return $this->_get_level($array[$id]['parent_id'],$array,$i);
        }
    }

    /**
     *  编辑墓区 信息
     */
    public function Information(){

        $selected_id_v = $this->request->param('selected_id_v');
        session('selected_id_v', isset($selected_id_v)?$selected_id_v:'0');
	    if ($this->request->isPost()){
	       $param = $this->request->param();
	       $col_id = explode(',',$param['col_id']);
	       $id = explode(',',$param['id']);
            // 艺术墓 - 且 - 有order_id  修改其档案编号，档案编号不能重复
            if(!empty($param['order_id'])){
                $order_info = Db::name("order")->where(['order_id'=>$param['order_id']])->find();
                if ($order_info){
                    if($param['archives_sn']){
                        $order_ex = Db::name("order")->where('order_id',"<>",$param['order_id'])->where(array('archives_sn'=>$param['archives_sn']))->select()->toArray();
                        if($order_ex){
                            $this->error('档案编号已存在');
                        }else{
                            $o_data['archives_sn'] = $param['archives_sn'];
                            $res   =  Db::name("order")->where(['order_id'=>$param['order_id']])->update($o_data);
                        }
                    }else{
                        $this->error('档案编号不能为空');
                    }
                }
            }

	       foreach ($col_id as $key=>&$value){
//               $tomb_address = Db::name('tombarea_row_col')->where('colID',$value)->find();
               $tomb_address = Db::name('tombarea_row_col')->alias('c')
                   ->join('dj_tombarea_row r','  c.rowid = r.rowID')
                   ->join('dj_tombarea t','r.tombarea_id = t.id')
                   ->field('c.colID,c.num,c.rowid,r.tombarea_id,t.cate_id,c.reacher,t.cemetery_id,t.name tomb_address,c.rows_num tomb_loor,c.column_num tomb_bit_number ')
                   ->where('c.colID',$value)->find();

               $tomb_region = $this->getSup($tomb_address['cemetery_id']);
               $region = '';
               $region_row = '';
               if (isset($param['layer_num'])){
                   $region_row = $param['layer_num'].'层';
               }else{
                   $region_row = $tomb_address['tomb_loor'].'排';
               }
               foreach ($tomb_region as $k=>&$v){
                   if ($v['parent_id']!=0) {
                       $region = $v['name'] . $region;
                   }
               }

               $data =[
                   'tomb_id'=>$value,
                   'tomb_num'=>$tomb_address['num'],
                   'tombar_id'=>$tomb_address['tombarea_id'],
                   'cemetery_id'=>$tomb_address['cemetery_id'],
//                   'tomb_sn'=>$tomb_sn[$key],
                   'cate_id'=>$param['cate_id'], //类型
                   'pro_status'=>$param['pro_status'], //类型
                   'funeral'=>isset($param['funeral'])?$param['funeral']:'',//墓穴规制
                   'tomb_regulation'=>isset($param['tomb_regulation'])?$param['tomb_regulation']:'',
                   'footprint'=>isset($param['footprint'])?$param['footprint']:'',//墓碑高度/空间高度/左右长度
                   'tombstone_w'=>isset($param['tombstone_w'])?$param['tombstone_w']:'',//占地宽度/空间宽度/纵深宽度
                   'tombstone_h'=>isset($param['tombstone_h'])?$param['tombstone_h']:'',//墓碑高度/空间高度/左右长度
                   'single_cavity_size'=>!empty($param['sc_width'])?$param['sc_width'].'*'.$param['sc_height'].'*'.$param['sc_thick']:'',//单穴最大
                   'convergence'=>isset($param['convergence'])?$param['convergence']:'',//收敛形式
                   'specifications'=>isset($param['green_belt'])?$param['specifications']:'',//拜道规格
                   'green_belt'=>isset($param['green_belt'])?$param['green_belt']:'', // 绿化带
                   'greenbelt_num'=>isset($param['greenbelt_num'])?$param['greenbelt_num']:'',
                   'maintain'=>isset($param['maintain'])?$param['maintain']:'',//墓穴维护期  ,
                   'warranty'=>isset($param['warranty'])?$param['warranty']:'',//质保期
                   'is_bye'=>isset($param['is_bye'])?$param['is_bye']:0,//1含拜道0不
                   'limit_height'=>isset($param['limit_height'])?$param['limit_height']:'',//限制高度
                   'design'=>isset($param['design'])?$param['design']:'',//设计墓穴
                   'periphery'=>isset($param['periphery'])?$param['periphery']:'',//外围设置
                   'current_make'=>isset($param['current_make'])?$param['current_make']:'',//当前制作
                   'new_pro'=>isset($param['new_pro'])?$param['new_pro']:'',//新产品
                   'old_pro'=>isset($param['old_pro'])?$param['old_pro']:'',//以旧换新产品
                   'product_mb_base_id'=>isset($param['product_mb_base_id'])?$param['product_mb_base_id']:'',
                   'product_mb_base_id1'=>isset($param['product_mb_base_id'])?$param['product_mb_base_id1']:'',
                   'product_info_id'=>isset($param['product_info_id'])?$param['product_info_id']:'',
                   'selling_price'=>isset($param['selling_price'])?$param['selling_price']:'',//售价
                   'menu_type'=>isset($param['menu_type'])?$param['menu_type']:'',//售价单位
                   'tomb_region'=>$region,//墓位所在区域
                   'tomb_address'=>$tomb_address['tomb_address'],//所在位置
                   'layer_num'=>$region_row,//所在排
                   'tomb_bit_number'=>$tomb_address['tomb_bit_number'].'号位',//所在位号
                   'add_user'=>cmf_get_current_admin_id(),
                   'remark'=>isset($param['remark'])?$param['remark']:'',//备注
               ];


               if ($param['cate_id']==2){
                   $data['tom_img']=$param['upload_plan'];
               }else{
                   $data['tom_img']=$param['tom_img'];
               }
               if ($param['substitute']){
                   Db::name('tombarea_row_col')->where(['colID'=>$value])->update(['reacher'=>$param['substitute']]);
               }else{
                   Db::name('tombarea_row_col')->where(['colID'=>$value])->update(['reacher'=>'']);
               }
               Db::name("tomb_mb")->where(['tomb_id'=>$value,'type'=>0])->delete();
               if ($param['cate_id']==2) {
                   if (isset($param['mb'])) {
                       foreach ($param['mb'] as $km => &$valuem) {
                           if (!empty($valuem['dele_info_mb_id'])) {
                               Db::name("tomb_mb")->where(['tomb_id' => $value, 'id' => $valuem['dele_info_mb_id'], 'type' => 0])->delete();
                           } else {
                               if (!empty($valuem['mb_id'])) {
                                   $mb_info = [
                                       'tomb_id' => $value,
                                       'mb_id' => $valuem['mb_id'],
                                       'mb_name' => $valuem['mb_name'],
                                       'address' => $valuem['address'],
                                       'regulation' => $valuem['regulation'],
                                       'status' =>1,
                                       'type' => 0,
                                   ];
                                   if (!empty($valuem['mb_id_id'])) {
                                       Db::name("tomb_mb")->insertGetId($mb_info);
                                   } else {
                                       Db::name("tomb_mb")->insertGetId($mb_info);
                                   }
                               }
                           }
                       }
                       TombareaRowColModel::update(['col_status' => 1],['colID' => $value,'col_status'=>4]);
                   }
                   if (isset($param['other'])) {
                       foreach ($param['other'] as $ko => &$valueother) {
                           if (!empty($valueother['dele_product_info_id'])) {
//                           Db::name('product_mb_info')->where(['id' => $valueother['dele_product_info_id']])->delete();
                               Db::name("tomb_mb")->where(['tomb_id' => $value, 'mb_info_id' => $valueother['dele_product_info_id'], 'type' => 7])->delete();
                           } else {
                               $product_info = array(
                                   'itype' => 7,
                                   'mb_id' => $value,
                                   'iname' => $valueother['iname'],
                                   'iwidth' => $valueother['iwidth'],
                                   'iheight' => $valueother['iheight'],
                                   'ithick' => $valueother['ithick'],
                                   'icate' => $valueother['icate'],
                                   'inumber' => $valueother['inumber'],
                                   'imaterial_price' => $valueother['imaterial_price'],
                                   'irepair_price' => $valueother['irepair_price'],
                                   'ichange_price' => $valueother['ichange_price'],
                                   'isort' => $valueother['isort'],
                                   'add_time' => time(),
                                   'add_user' => cmf_get_current_admin_id(),
                               );
                               if (!empty($valueother['product_info_id'])) {
                                   $res = Db::name('product_mb_info')->where('id', $valueother['product_info_id'])->update($product_info);
                                   $mb_info_id = $valueother['product_info_id'];
                                   $product_info_arr[] = $product_info;
                               } else {
                                   $mb_info_id = Db::name('product_mb_info')->insertGetId($product_info);
                               }
                               if (!Db::name("tomb_mb")->where(['tomb_id' => $value, 'mb_info_id' => $mb_info_id, 'type' => 7])->find()) {
                                   $mb_infos = [
                                       'tomb_id' => $value,
                                       'mb_id' => $valuem['mb_id'],
                                       'mb_name' => '',
                                       'mb_info_id' => $mb_info_id,
                                       'address' => $valuem['address'],
                                       'status' => 1,
                                       'type' => 7,
                                   ];
                                   Db::name("tomb_mb")->insertGetId($mb_infos);
                               }
                           }
                       }
                   }
               }
               $information_info = Db::name("tombarea_information_product")->where(['tomb_id'=>$value])->find();

               if ($information_info){
                   $res   =  Db::name("tombarea_information_product")->where(['id'=>$information_info['id']])->update($data);
               }else{
                   $data['add_time'] = time();
                   $res   =  Db::name("tombarea_information_product")->insertGetId($data);
               }
               if ($res !==false) {
                   if ($param['cate_id'] == 1) {
                       TombareaRowColModel::update(['col_status' => 0], ['colID' => $value, 'col_status' => 4]);
                   } else {
                       if (empty($information_info['new_pro'])) {
                           TombareaRowColModel::update(['col_status' => 1],['colID' => $value,'col_status'=>0]);
                       }
                   }
               }
           }

           if ($res !==false){
               return $this->success("保存成功",url("visua/index"));
           }else{
               return $this->error('操作失败');
           }
        }

	    $id = $this->request->param('col_id');
        $order_id = $this->request->param('order_id');
	    $info = Db::name('tombarea_row_col')->alias('c')
            ->join('dj_tombarea_row r','  c.rowid = r.rowID')
            ->join('dj_tombarea t','r.tombarea_id = t.id')
            ->field('c.colID,c.num,c.rowid,r.tombarea_id,t.cate_id,c.reacher,t.cemetery_id,t.name tomb_address,c.rows_num tomb_loor,c.column_num tomb_bit_number ')
            ->whereIn('c.colID',$id)->find();

        $num='';
	    if ($info){
            $colID = Db::name('tombarea_row_col')->whereIn('colID',$id)->column('colID');
            $num = Db::name('tombarea_row_col')->whereIn('colID',$id)->column('num');
            $num = implode(',',$num);
            $result = Db::name('tombarea_information_product')->whereIn('tomb_id',$colID)->where(['cate_id'=>$info['cate_id']])->find();
            $result_id = Db::name('tombarea_information_product')->whereIn('tomb_id',$colID)->where(['cate_id'=>$info['cate_id']])->column('id');

            if ($result){
                if ($result['single_cavity_size']) {
                    $single_cavity_size = explode('*', $result['single_cavity_size']);
                    $result['sc_width'] = $single_cavity_size[0];
                    $result['sc_height'] = $single_cavity_size[1];
                    $result['sc_thick'] = $single_cavity_size[2];
                }
            }
            $result['substitute'] = $info['reacher'];
            $cate_id = $info['cate_id'];

            if ($cate_id==2){
                $tomb_mb_list = Db::name("tomb_mb")->where(['tomb_id'=>$colID,'type'=>0])->select();
                $result['infoData'] = $tomb_mb_list;
                // 根据ORDER_ID 获取档案号
                if($order_id){
                    $order_info = Db::name("order")->field("archives_sn")->where(['order_id'=>$order_id])->find();
                    $this->assign("archives_sn", $order_info['archives_sn']);
                }
            }
            $cate_type = Db::name("stuff")->alias('s')->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name,s.stuff_money,s.stuff_unit")->join("dj_cate c", "c.id = s.cate_id", "left")->select();

            $mb_info_id= Db::name("tomb_mb")->where(['tomb_id'=>$colID,'type'=>7])->column('mb_info_id');
            $product_info = Db::name('product_mb_info')->whereIn('id',$mb_info_id)->select();
        }

        // 抵顶人
        $diding = Db::name("user")->alias("u")->field("user_nickname")
            ->join("dj_department d","d.id = u.dept_id","left")
            ->where("d.dept_type",7)
            ->where("u.user_status",1)
            ->select();
        $this->assign("didingList", $diding);
        $this->assign("product_info",$product_info);
        $this->assign("cate_type", $cate_type);
        $this->assign("cateJson", json_encode($cate_type));

        $this->assign('info',$info);
        $this->assign('selected_id_v',$selected_id_v);
	    $this->assign('result',$result);
	    $this->assign('num_sn',$num);
	    $this->assign('col_id',$id);
        $this->assign('order_id',$order_id);
        $mblist=  Db::name('product')->where(['pro_type'=>$cate_id,'pro_status'=>1])->select();
//      exit(json_encode($mblist));
        $mb_arr=[];
        foreach ($mblist as $km=>&$vals){
            $m_info['id'] = $vals['id'];
            $m_info['pro_name'] = $vals['pro_name'].'('.$vals['pro_code'].')【'.$this->regulation_arr[$vals['regulation']].'】';
            $m_info['pro_code'] = $vals['pro_code'];
            $m_info['pro_photo'] = $vals['pro_photo'];
            $m_info['pro_length'] = $vals['pro_length'];
            $m_info['pro_width'] = $vals['pro_width'];
            $m_info['pro_height'] = $vals['pro_height'];
            $m_info['pro_photo_path'] = cmf_get_image_preview_url($vals['pro_photo']);
            $mb_arr[]=$m_info;
        }

        $this->this_tomb();
        $this->assign('mb_list',$mb_arr);
        $this->assign('cate_id',$cate_id);
        return $this->fetch();

    }
    public function getProductMbInfo(){
        $result=[];
        $parem = $this->request->param();
        $id = $parem['id'];
        if ($parem['type']==1){
            $result=[];
        }elseif ($parem['type']==2){
            $result['product_mb_base'] = Db::name('product_mb_base')->where('product_id', $id)->select();
            $result['product_info'] = Db::name('product_info')->where(['pro_id'=>$id])->select();
        }elseif ($parem['type']==3){
        }elseif ($parem['type']==4){

            $result=[];
        }
        return $this->result($result);
    }

    /**
     * 添加墓位
     */
    public function add_tomb_col(){
        $selected_id_v = $this->request->param('selected_id_v');
        session('selected_id_v', isset($selected_id_v)?$selected_id_v:'0');
        if ($this->request->isPost()){
            $data = $this->request->param();

            $col_arr = $data['col'];
            $col = TombareaRowColModel::where("num",$data['num'])->find();
            if(!empty($col)) {
               return $this->error($data['num'] . '墓位排号重复');
            }

            $col_insert = [
                'cate_id'=>$data['cate_id'],
                'num'=>$data['num'],
                'reacher'=>$data['reacher'],
                'column_num'=>$data['column_num'],//位 序号
                'rowid'=>$data['rowid'],
                'rows_num'=>isset($data['rows_num'])?$data['rows_num']:'',
                'tombarea_id'=>$data['tombarea_id'],
                'status'=>$data['status'],
                'col_status'=>4,
            ];
            TombareaRowColModel::insert($col_insert);

            foreach ($col_arr as $key=>&$value){
                TombareaRowColModel::update(['column_num'=>$value['column_num']],['colID'=>$value['id']]);
            }
            Db::name('tombarea_row')->where(['rowID'=>$data['rowid']])->update(['column'=>count($col_arr)+1]);
            $this->success('添加成功',url('index'));
        }

        $tombar_id = $this->request->param('tombar_id');

        $ajax = $this->request->param('ajax',0);
        if ($ajax==1){
            $rowid =$this->request->param('rowid');
            $row = TombareaRowColModel::where(['rowid'=>$rowid])->select();
            exit(json_encode($row));
        }
       $tombarea_info =  Db::name('tombarea')->where(['id'=>$tombar_id])->find();
       $row_list =  Db::name('tombarea_row')->where(['tombarea_id'=>$tombar_id])->select();
        $reacher_list = dept_per(7);
        $this->assign([
            'reacher_list'=>$reacher_list,
            'tombarea_info'=>$tombarea_info,
            'row_list'=>$row_list,
            'tombarea_id'=>$tombar_id,
            'selected_id_v'=>$selected_id_v
        ]);
        return $this->fetch('add_tomb_col');
    }
    /**
     * 删除墓位
     */
    public function tombareacoldelete(){
        if ($this->request->isGet()) {
            $param = $this->request->param();

            $selected_id_v = $this->request->param('selected_id_v');
            session('selected_id_v', isset($selected_id_v)?$selected_id_v:'0');
            $status= true;
            Db::startTrans();
            $col_id = explode(',', $param['id']);
            try{
                foreach ($col_id as $k=>&$value){
                    $res_info = Db::name('tombarea_row_col')->where(['colID'=>$value])->find();
                    if ($res_info){
                        if ($res_info['col_status']==0){
                            $msg_[$k+1] = 1;
                            $res1 = Db::name('tombarea_row_col')->where(['colID'=>$value])->delete();
                            $res_info = Db::name('tombarea_row')->where(['rowID'=>$res_info['rowid']])->setDec('column',1);
                            if($res1) {
                                $status = true;
                            }else{
                                $status = false;
                            }
                        } else{
                            $status = false;
                        }
                    } else{
                        $status = false;
                    }
                }
                if($status){
                    Db::commit();
                    $this->success('删除成功',url('index',array("selected_id_v",$this->selected_id_v)));
                }else{
                    Db::rollback();
                    $this->error('删除失败',url('index',array("selected_id_v",$this->selected_id_v)));
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error('删除失败',url('index',array("selected_id_v",$this->selected_id_v)));
            }
        }
    }

    /**
     *  保留
     */
    public function tombareacolretain(){
        $param = $this->request->param();
        $status = true;
        $col_id = explode(',', $param['id']);
        foreach ($col_id as $k=>&$value) {
            $res_info = Db::name('tombarea_row_col')->where(['colID' => $value])->find();
            if ($res_info) {
                if ($res_info['col_status'] != 6 || $res_info['col_status'] != 7 ) {
                    $msg_[$k + 1] = 1;
                    $res1 = Db::name('tombarea_row_col')->where(['colID' => $value])->update(['col_status' =>2]);
                    if(!$res1) {
                        $status = false;
                    }
                }
            }
        }
        if( $status){
            $this->success('保留成功',url('index',array("selected_id_v",$this->selected_id_v)));
        }else{
            $this->error('保留失败');
        }
    }
    /**
     * 取消保留
     */
    public function tombCancelReservation(){
        $param = $this->request->param();
        $status = true;
        $col_id = explode(',', $param['id']);
        foreach ($col_id as $k=>&$value) {
            $info = Db::name('tombarea_row_col')->where(['colID' => $value])->find();
            $product_info = Db::name('tombarea_product')->where(['tombar_id' => $info['rowid']])->find();
            if ($info){
                if ($info['col_status'] != 6 || $info['col_status'] != 7 ) {
                    if ($product_info) {
                        Db::name('tombarea_row_col')->where(['colID' => $value])->update(['col_status' => 1]);
                    } else {
                        Db::name('tombarea_row_col')->where(['colID' => $value])->update(['col_status' => 0]);
                    }
                }else{
                    $status = false;
                }
            }
        }
        if( $status){
            $this->success('取消保留成功',url('index',array("selected_id_v",$this->selected_id_v)));
        }else{
            $this->error('取消保留失败！');
        }
    }

    /**
     * 隐藏
     */
    public function tombCancelhide(){
        $param = $this->request->param();
        $status = true;
        $col_id = explode(',', $param['id']);
        foreach ($col_id as $k=>&$value) {
            $info = Db::name('tombarea_row_col')->where(['colID' => $value])->find();
            if ($info){
                $status = Db::name('tombarea_row_col')->where(['colID' => $value])->update(['status' => 2]);
            }
        }
        if( $status){
            $this->success('隐藏成功',url('index',array("selected_id_v",$this->selected_id_v)));
        }else{
            $this->error('隐藏失败！');
        }
    }

    /**
     * 取消隐藏
     */
    public function tombCancelUnhide(){
        $param = $this->request->param();
        $status = true;
        $col_id = explode(',', $param['id']);
        foreach ($col_id as $k=>&$value) {
            $info = Db::name('tombarea_row_col')->where(['colID' => $value])->find();
            if ($info){
                $status = Db::name('tombarea_row_col')->where(['colID' => $value])->update(['status' => 1]);
            }
        }
        if( $status){
            $this->success('取消隐藏成功',url('index',array("selected_id_v",$this->selected_id_v)));
        }else{
            $this->error('取消隐藏失败！');
        }
    }
    /**
     * 合并
     */
    public function tombMerge(){
        $param = $this->request->param();
        $status = true;
        $col_id = explode(',', $param['id']);
        if( $status){
            $this->success('取消合并成功',url('index',array("selected_id_v",$this->selected_id_v)));
        }else{
            $this->error('取消合并失败！');
        }
    }
    /**
     * 取消合并
     */
    public function tombCancelMerge(){
        $param = $this->request->param();
        $status = true;
        $col_id = explode(',', $param['id']);
        if( $status){
            $this->success('取消合并成功',url('index',array("selected_id_v",$this->selected_id_v)));
        }else{
            $this->error('取消合并失败！');
        }
    }
    public function prodelete(){
        $id = $this->request->param("id",0,'intval');
        $type = $this->request->param("type",0,'intval');
        if ($type==1){
            Db::name("product_mb")->where('id', $id)->delete();
            Db::name("product_mb_info")->where('pro_id', $id)->delete();
            Db::name("product_mb_annex")->where('mb_id', $id)->delete();
            Db::name("tomb_mb")->where('mb_id', $id)->delete();
            return $this->success('重置成功。请重新填写墓碑产品信息');
        }
    }
    /**
     * 下拉数据
     */
    public function getALlOption()
    {
        $cate_type = Db::name("stuff")->alias('s')
            ->field("s.id,concat(c.cate_name,'-',s.stuff_name) as name,s.stuff_money,s.stuff_unit")
            ->join("dj_cate c", "c.id = s.cate_id", "left")->select();
        $this->assign("cate_type", $cate_type);
        $this->assign("cateJson", json_encode($cate_type));
        // 所有产品库
        $allData = Db::name("product")->field("id,pro_name as name")->select();
        $this->assign("allData", $allData);
        // 附件
        $annex = Db::name("annex")->field("id,annex_name as name")->select();
        $this->assign("annex", $annex);
        $this->assign("annexJson", json_encode($annex));
    }

    public function this_tomb(){
        $queue_regulation = config('queue.regulation');
        $queue_convergence = config('queue.convergence');
        $queue_funeral = config('queue.funeral');
        $queue_periphery = config('queue.periphery');
        $this->assign('tomb_regulation',$queue_regulation);
        $this->assign('tomb_funeral',$queue_funeral);
        $this->assign('tomb_convergence',$queue_convergence);
        $this->assign('tomb_periphery',$queue_periphery);
    }

}
